package ltd.hxya.novel.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.models.auth.In;
import ltd.hxya.novel.admin.entity.Operation;
import ltd.hxya.novel.admin.mapper.OperationMapper;
import ltd.hxya.novel.admin.service.IOperationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hxya.novel.admin.vo.OperationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hty
 * @since 2022-10-04
 */
@Service
public class OperationServiceImpl extends ServiceImpl<OperationMapper, Operation> implements IOperationService {

    @Autowired
    OperationMapper operationMapper;

    @Override
    public List<Operation> operaByUserId(Integer userId) {
        List<Operation> operations = operationMapper.operationsByUserId(userId);
        return operations;
    }

    @Override
    public List<OperationVo> operationTree() {
        QueryWrapper<Operation> operationQueryWrapper = new QueryWrapper<>();
        //查询出为菜单的集合
        operationQueryWrapper.eq("type",0);
        List<Operation> operationAll = this.baseMapper.selectList(operationQueryWrapper);
        //首先查询父id为0的菜单
        List<OperationVo> operationVos = getOperation(operationAll, 0);

        return operationVos;
    }

    private List<OperationVo> getOperation(List<Operation> operationAll, Integer parentId) {

        List<Operation> operations = new ArrayList<>();
        for (Operation operation : operationAll) {
            if (!StringUtils.isEmpty(operation.getParentId())&&operation.getParentId().equals(parentId)){
                operations.add(operation);
            }
        }
        //TODO 对菜单排序
        operations.sort(new Comparator<Operation>() {
            @Override
            public int compare(Operation o1, Operation o2) {
                return o1.getSort()-o2.getSort();
            }
        });


        if (CollectionUtils.isEmpty(operations)){
            return null;
        }
        List<OperationVo> operationVos = operations.stream().map(operation -> {
            OperationVo operationVo = new OperationVo();
            BeanUtils.copyProperties(operation, operationVo);
            operationVo.setChildren(getOperation(operationAll, operation.getOperationId()));
            if (StringUtils.isEmpty(operationVo.getComponent())){
                operationVo.setComponent("Layout");
            }
            return operationVo;
        }).collect(Collectors.toList());
        return operationVos;
    }
}
